#! -*- coding: utf-8 -*-
"""
    邮件功能函数
    不同类型的邮件处理函数，后期可将起封装成一个邮件发送类
"""
import logging
import requests

from flask import current_app

from .misc import smart_str


logger = logging.getLogger('vacation_email')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('[%(asctime)s] %(name)s: %(levelname)s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)


def send_email(title, mail_body, to_email):
    data = {
        "to": to_email,
        "from": "hi@email.breadtrip.com",
        "from_name": u"面包旅行",
        "subject": title,
        "body": mail_body,
        "mail_type": "USER",
    }

    try:
        mc_url = "%s/mail/send/" % current_app.config['EMAIL_HOST']
        print current_app.config['EMAIL_HOST']
        print mc_url
        res = requests.post(mc_url, json=data).json()
    except Exception as e:
        logger.error("Send email to %s failed, exception: %s " % (to_email, e))
        return False

    if res.get('ok'):
        logger.info("Send email to %s success" % (to_email))
        return True

    logger.info("Send email to %s failed, reason: %s" % (to_email, res.get('reason')))
    return False


def send_staff_dialog_email(name, username, text, date):
    content = """
        <p>亲爱的管理员</p>
        <p>刚刚收到一条关于&ldquo;%s&rdquo;的新消息，请尽快查看，消息内容如下：</p>
        <hr />
        <div style="background-color: #f22f2f2; padding: 10px;">
        <h4>%s：</h4>
        <p>%s</p>

        <p>%s</p>
        </div>
        <p style="text-align: center;"><a href="http://vacation.breadtrip.com/dashboard/TH/statistics/poi/dialog/">点击查看</a></p>
        <hr />
        <p>下面的话是为了提高匹配度</p>
        <ul style="margin: 5px 0 37px 0;padding: 0;color: #999999; list-style: none; font-size: 14px; line-height: 20px;">
            <li style="list-style-type: none;">&bull; 您可以随时登陆您的【面包自由行】客户端 ，查询您的订单详情。并对订单进行取消，查看出游凭证等操作。</li>
            <li style="list-style-type: none;">&bull; 请您在出行前，仔细阅读您购买旅行产品服务的预订须知，让您的行程更加畅通无阻。</li>
            <li style="list-style-type: none;">&bull; 关于【面包自由行】服务的完整信息，请查看【面包自由行】服务条款。</li>
            <li style="list-style-type: none;">&bull; 如果您有任何疑问或建议，请联系我们。 电话：<b style="font-weight: bold;">400-625-1066</b>, 微信服务号：<b style="font-weight: bold;">玩遍泰国</b></li>
            <li style="list-style-type: none;">&bull; 本邮件由【面包自由行】系统自动发出，请勿直接回复</li>
        </ul>
        <p style="list-style-type: none;">&nbsp;</p>
        <p>【面包自由行】是专业的一站式自由行服务提供商。我们的应用可以帮您轻松在手机上安排行程、预订旅行产品，是您泰国旅行的不二之选。</p>
        """
    title = u'有新的poi问答消息啦'
    name = smart_str(name)
    username = smart_str(username)
    text = smart_str(text)
    content = content % (name, username, text, date)
    # tasks.send_email.delay(title, content, ORDER_REMIND_EMAILS,
    #                        content_subtype='html',
    #                        send_seperately=False)
    return
